package com.bountytask.service.impl;
import com.bountytask.dao.TaskDao;
import com.bountytask.dao.UserDao;
import com.bountytask.dao.UserTaskDao;
import com.bountytask.entity.Task;
import com.bountytask.entity.UserInfo;
import com.bountytask.entity.UserTask;
import com.bountytask.service.UserAndTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.dsig.keyinfo.RetrievalMethod;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class UserAndTaskServiceImpl implements UserAndTaskService {
    @Autowired
    private TaskDao taskDao;
    @Autowired
    private UserTaskDao userTaskDao;
    @Autowired
    private UserDao userDao;

    //根据任务状态，任务角色（发布人/执行人）获取用户任务关联数据
    public List<Task> findTaskByStatus(long userId,int role,int status){
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("role",role);
        map.put("status",status);
        List<Long> taskIds=taskDao.getTaskIds(map);
        if (taskIds.size()==0)return null;
        return taskDao.getTaskByIds(taskIds);
    }

    //根据用户和任务id修改执行人的任务状态
    @Transactional
    public int updateForSubmit(long userId,long taskId){
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("taskId",taskId);
        if (userTaskDao.getStatus(map)==2)
            return 400;
        Task task=taskDao.getTaskById(taskId);
        task.setFinishNum(task.getFinishNum()+1);
        if (userTaskDao.updateExecutorForSubmit(map)!=1 || userTaskDao.updatePosterForSubmit(taskId)!=1
                ||taskDao.updateTask(task)!=1)
            return 400;
        return 200;
    }

    //确认提交的任务
    @Transactional
    public int confirmTask(long userId,long taskId){
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("taskId",taskId);
        //如果不是该提交任务的人的状态不是待确认，则任务发布人不需要确认
        if (userTaskDao.getStatus(map)!=2)
            return 400;
        //更新任务状态
        if (userTaskDao.updateExecutorForConfirm(map)!=1 || userTaskDao.updatePosterForConfirm(taskId)!=1)
            return 400;
        Task task= taskDao.getTaskById(taskId);
        //更新user数据
        UserInfo user=userDao.getUserById(userId);
        user.setMoney(user.getMoney()+task.getBounty());
        user.setFinishNum(user.getFinishNum()+1);
        if(userDao.updateUserInfo(user)!=1)
            return 400;
        //更新任务数据
//        task.setFinishNum(task.getFinishNum()+1);
//        if (taskDao.updateTask(task)!=1)
//            return 400;
        return 200;
    }

    //下线任务
    @Transactional
    public int offlineTask(long userId,long taskId){
        List<Integer> statuses=userTaskDao.getStatuses(taskId);
        for (Integer status : statuses) {
            if (status > 1)
                return 400;
        }
        //让发布者任务状态-1即可变为0，因此直接调用这个方法
        if (userTaskDao.updatePosterForConfirm(taskId)!=1)
            return 400;
        Task task = taskDao.getTaskById(taskId);
        task.setTaskStatus(1);
        if (taskDao.updateTask(task)!=1)
            return 400;
        UserInfo user = userDao.getUserById(userId);
        user.setMoney(user.getMoney()+task.getTaskNumber()*task.getBounty());
        if (task.getGetNum()!=0)
            user.setSettleNum(user.getSettleNum()+1);
        if (userDao.updateUserInfo(user)!=1)
            return 400;
        return 200;
    }

    /**
     * 根据任务id返回任务发布者id，任务执行者id，以及其在该任务的状态
     * @param taskid
     * @return
     */
    public List<UserTask> getUserTaskId(long taskid){
        List<UserTask> userTasks=userTaskDao.getUserIdAndTaskid(taskid);
        List<UserTask> userTasks1=userTaskDao.getUserIdAndTaskid2(taskid);
        userTasks.addAll(userTasks1);
        return userTasks;
    }

    /**
     * 根据角色获得该用户在该任务下的状态
     */
    @Transactional
    public int getOneStatus(long userid,long taskid){
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",userid);
        map.put("taskId",taskid);
        int status;
        //判断是否被认定无效，如果是，则会报错
        try {
           status=userTaskDao.getStatus(map);
        }catch (org.apache.ibatis.binding.BindingException e){
            try {
                status=userTaskDao.getStatusNoDel(map);
            }catch (org.apache.ibatis.binding.BindingException e1){
                //不根据del_tag字段查找都找不到数据的话，说明前端传的id是错的
                return 400;
            }
            //被认定无效
            status=-1;
        }
        return status;
    }

    //获得所有的执行者id
    public HashMap<Long,List<Long>> getAllExecutor(List<Long> taskIds){
        HashMap<Long, List<Long>> taskExecutorMap = new HashMap<>();
        for (int i = 0; i < taskIds.size(); i++) {
            List<Long> executors = userTaskDao.getExecutors(taskIds.get(i));
            taskExecutorMap.put(taskIds.get(i),executors);
            executors.clear();
        }
        return taskExecutorMap;
    }

    public long getPoster(long taskId){
        return userTaskDao.getPoster(taskId);
    }
}
